import { ChunkEntityUpdateType, SysOrder } from "../../GameDef";
import { ECSEntity } from "../../lib/kgame/ecs/ECSEntity";
import { IECSFilter } from "../../lib/kgame/ecs/ECSFilter";
import { ECSSys } from "../../lib/kgame/ecs/ECSSys";
import { CmpChunkEntity } from "../cmp/CmpChunkEntity";
import { SCmpWorld } from "../scmp/SCmpWorld";

/**
 * 区块系统
 */
export class SysChunk extends ECSSys {

    world: SCmpWorld;

    get updateOrder(): number {
        return SysOrder.chunk;
    }

    get ifilter(): IECSFilter {
        return { includeAll: [CmpChunkEntity] }
    }

    protected onStart(): void {
        this.world = this.scene.getCmp(SCmpWorld);
    }

    onDestroy(): void {
        this.world = null;
    }

    protected onEntityAdd(entity: ECSEntity): void {
        const chunkEntity = entity.getCmp(CmpChunkEntity);
        this.world.chunk.addItem(chunkEntity, chunkEntity.aabb);
}
    
    protected onEntityRemove(entity: ECSEntity): void {
        const chunkEntity = entity.getCmp(CmpChunkEntity);
        this.world.chunk.removeItem(chunkEntity);
    }

    protected onUpdateEntity(entity: ECSEntity): void {
        const world = this.scene.getCmp(SCmpWorld);
        const cmp = entity.getCmp(CmpChunkEntity);
        if (cmp.updateType === ChunkEntityUpdateType.update) {
            world.chunk.updateItem(cmp, cmp.aabb);
        }
    }

}